const __icon_util = require('./util')
const __icon_fs = require('fs')
const __icon_path = require('path');
const __icon_os = require('os');
const __icon_app = require('electron').remote.app;
const __icon_child_process = require('child_process');

const __icon_base_path = __icon_path.resolve(__icon_os.homedir(), __icon_app.getPath('documents'), 'mac-quick-start', 'icons');

var __icon_cachedIconPath = function (appId) {
    return __icon_path.join(__icon_base_path, appId + '.png');
}

var __icon_makeCachedIcon = function (appId, appPath) {
    if(!__icon_fs.existsSync(__icon_base_path)){
        __icon_fs.mkdirSync(__icon_base_path);
    }

    var icon = __icon_cachedIconPath(appId);
    if (__icon_fs.existsSync(icon)) {
        return icon;
    }

    var appResourcePath = __icon_path.join(appPath, 'Contents/Resources/');
    if (__icon_fs.existsSync(appResourcePath)) {
        var files = __icon_fs.readdirSync(appResourcePath);
        var icnsFile = null;
        if (files && files.length > 0) {
            for (var i in files) {
                if (files[i].toLowerCase().endsWith('.icns')) {
                    icnsFile = __icon_path.join(appResourcePath, files[i]);
                    break;
                }
            }
            if (icnsFile) {
                __icon_makeIconByShell(icnsFile, icon);
                return icon;
            }
        }
    }
    return null;
}

var __icon_makeIconByShell = function (icnsFile, pngFile) {
    __icon_child_process.spawnSync(
        'sips',
        ['-Z', '128', '-s', 'format', 'png', icnsFile, '--out', pngFile],
        {
            stdio: 'ignore',
            encoding: 'utf-8',
            shell: false,
            timeout: 30 * 1000
        });
}

var __icon_resolveIcon = function (iconFile) {
    var realicon;
    if(!iconFile){
        return null;
    }

    if(iconFile.startsWith('embed://')){
        realicon = __icon_util.resolvePath(path.join('./res/icon',iconFile.substr(8)));
    }else{
        realicon = __icon_util.getUserPath(iconFile);
    }
    console.log(realicon);
    
    return realicon;
}


module.exports.icons = {
};
module.exports.cachedIconBasePath = __icon_base_path;
module.exports.default_icon = __icon_util.resolvePath('./res/icon/default.png');
module.exports.makeCachedIcon = __icon_makeCachedIcon;
module.exports.getCachedIconPath = __icon_cachedIconPath;
module.exports.resolveIcon = __icon_resolveIcon;